<template>
  <div>
    <div ref="myPage" style="height:calc(100vh - 50px);" @click="isShowNodeMenuPanel = false">

      <el-row :gutter="20">
        <el-col :span="16">
          <div :style="{width: myGraphPanelSize.width + 'px',height:myGraphPanelSize.height + 'px'}" style="border:rgba(90,187,181,0) solid 1px;">
            <RelationGraph
              ref="seeksRelationGraph"
              :on-node-expand="onNodeExpand"
              :on-node-collapse="onNodeCollapse"
              :options="graphOptions">
              <div slot="node" slot-scope="{node}" @mouseover="showNodeTips(node, $event)" @mouseout="hideNodeTips(node, $event)">
                <!--
                <div slot="node" slot-scope="{node}" @mouseover="showNodeTips(node, $event)" @mouseout="hideNodeTips(node, $event)">
                -->
                <div @contextmenu.prevent.stop="showNodeMenus(node, $event)">
                  <!--div里面 style="height:80px;line-height: 80px;border-radius: 50%;cursor: pointer;"-->
                  <!--
                  <div style="color: #FFFFFF;font-size: 16px;position: absolute;width: 100px;height:25px;line-height: 25px;margin-top:5px;margin-left:0px;text-align: center;background-color: rgba(66,187,66,0);">
                    {{ node.text }}{{ "权值:"+node.data.value }}
                  </div>-->
                  <!--如果要修改值记得修改节点长宽匹配，可以绘制其他样式-->
                  <div style="width:200px;cursor: pointer;text-align: left;padding:0px;">
                    <div style="padding-left:10px;color:white">
                      {{ node.text }}
                    </div>
                    <div style="background-color: #f0f5f4;height: 80px;color:#555555;padding-left:10px;padding-top:10px;border-radius: 8px;">
                      <div style="border-bottom: #efefef solid 1px;">
                  <span :style="classObje(node.data.value)">
                    <i class="el-icon-s-help" />
                    <i class="el-icon-s-help" />
                    <i class="el-icon-s-help" />
                  </span>
                      </div>
                      <div style="border-bottom: #efefef solid 1px;">
                        <i class="el-icon-caret-right" />{{ "权值:"+node.data.value }}
                      </div>
                      <div style="border-bottom: #efefef solid 1px;">
                        <i  class="el-icon-caret-right" />{{ "权重:"+node.data.weight }}
                      </div>
                    </div>
                  </div>

                </div>
              </div>

            </RelationGraph>
          </div>
        </el-col>
        <el-col :span="8" style="text-align: right; margin-top: 10px;margin-bottom: 0px">
          <el-divider></el-divider>
          <el-descriptions title="树状图显示界面" :column="1" :data="currentNode" :style="{ width: myGraphTableSize.width + 'px' }" border>
            <template slot="extra">
              <el-button type="primary" round style="margin-right: 10px;" @click="doActionAdd(0)">生成新节点</el-button>
            </template>
          </el-descriptions>

        </el-col>

        <el-col :span="8" style="text-align: right; margin-top: 10px;margin-bottom: 0px" v-if="dataVisible">
          <el-descriptions title="" :column="1" :data="currentNode" :style="{ width: myGraphTableSize.width + 'px', height: myGraphTableSize.height + 'px' }" border>

            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-star-off"></i>
                节点名称
              </template>
              {{currentNode.text}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-connection"></i>
                节点ID
              </template>
              {{currentNode.id}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-finished"></i>
                节点权值
              </template>
              {{currentNode.data.value}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-tickets"></i>
                节点算子
              </template>
              <el-tag size="small">{{currentNode.data.oper}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-edit"></i>
                节点权重
              </template>
              {{currentNode.data.weight}}
            </el-descriptions-item>
          </el-descriptions>


        </el-col>
      </el-row>
      <!-- @contextmenu.prevent="showNodeMenus(node, $event)"
           @click="showNodeMenus(node, $event)"
           -->

    </div>
    <div v-if="isShowNodeTipsPanel" :style="{left: nodeMenuPanelPosition.x + 'px', top: nodeMenuPanelPosition.y + 'px' }" style="z-index: 999;padding:10px;background-color: #ffffff;border:#eeeeee solid 1px;box-shadow: 0px 0px 8px #cccccc;position: absolute;">
      <div style="line-height: 25px;padding-left: 10px;color: #888888;font-size: 12px;">节点名称：{{currentNode.text}}</div>
      <div class="c-node-menu-item">id:{{currentNode.id}}</div>
      <div class="c-node-menu-item">算子:{{currentNode.data.oper}}</div>
      <div class="c-node-menu-item">权重:{{currentNode.data.weight}}</div>
      <div class="c-node-menu-item">计算值:{{currentNode.data.value}}</div>
    </div>
    <div v-show="isShowNodeMenuPanel" :style="{left: nodeMenuPanelPosition.x + 'px', top: nodeMenuPanelPosition.y + 'px' }" style="z-index: 999;padding:10px;background-color: #ffffff;border:#eeeeee solid 1px;box-shadow: 0px 0px 8px #cccccc;position: absolute;">
      <div style="line-height: 25px;padding-left: 10px;color: #888888;font-size: 12px;">对这个节点进行操作：</div>
      <div class="c-node-menu-item" @click.stop="doAction('子节点增加')">子节点增加</div>
      <div class="c-node-menu-item" @click.stop="doAction('删除')">节点删除</div>
      <div class="c-node-menu-item" @click.stop="doAction('配置')">节点配置</div>
      <div class="c-node-menu-item" @click.stop="doAction('操作取消')">操作取消</div>
    </div>

    <div class="app-container">
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="指标id" prop="indicatorsId">
            <el-input v-model="form.indicatorsId" placeholder="请输入指标的id":disabled="true"/>
          </el-form-item>
          <el-form-item label="指标名称" prop="indicatorsName">
            <el-input v-model="form.indicatorsName" placeholder="请输入指标名称"/>
          </el-form-item>
          <el-form-item label="父节点" prop="father">
            <el-input v-model="form.father" placeholder="请输入父节点" oninput ="value=value.replace(/[^\d]/g,'')"/>
          </el-form-item>
          <el-form-item label="值" prop="value">
            <el-input v-model="form.value" placeholder="请输入值" oninput ="value=value.replace(/[^0-9.]/g,'')" />
          </el-form-item>
          <el-form-item label="权重" prop="weight">
            <el-input v-model="form.weight" placeholder="请输入权重" oninput ="value=value.replace(/[^0-9.]/g,'')" />
          </el-form-item>
          <el-form-item label="算子" prop="operator">
            <el-select v-model="form.operator" placeholder="请选择算子">
              <el-option
                v-for="item in options"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="指标描述" prop="indicatorsDesc">
            <el-input v-model="form.indicatorsDesc" placeholder="请输入指标描述" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="指标id" prop="indicatorsId">
            <el-input v-model="form.indicatorsId" placeholder="请输入指标的id":disabled="true"/>
          </el-form-item>
          <el-form-item label="指标名称" prop="indicatorsName">
            <el-input v-model="form.indicatorsName" placeholder="请输入指标名称"/>
          </el-form-item>
          <el-form-item label="父节点" prop="father">
            <el-input v-model="form.father" placeholder="请输入父节点" oninput ="value=value.replace(/[^\d]/g,'')"/>
          </el-form-item>
          <el-form-item label="值" prop="value">
            <el-input v-model="form.value" placeholder="请输入值" oninput ="value=value.replace(/[^0-9.]/g,'')" />
          </el-form-item>
          <el-form-item label="权重" prop="weight">
            <el-input v-model="form.weight" placeholder="请输入权重" oninput ="value=value.replace(/[^0-9.]/g,'')" />
          </el-form-item>
          <el-form-item label="算子" prop="operator">
            <el-select v-model="form.operator" placeholder="请选择算子">
              <el-option
                v-for="item in options"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="指标描述" prop="indicatorsDesc">
            <el-input v-model="form.indicatorsDesc" placeholder="请输入指标描述" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

    </div>
  </div>

</template>

<script>
import {tree_data } from "@/api/tree_config/tree_config";
import {getManage, delManage, addManage, updateManage, addNode} from "@/api/indicators/manage";
import { listOperators } from "@/api/ruoyi-operators/operators";

// 引入relation-graph
import RelationGraph from 'relation-graph';
var globalVariable = {
  value: 0,
  get() {
    // 在每次访问时返回当前值，并自增 1
    return this.value++;
  }
};
export default {
  name: 'Demo',
  components: { RelationGraph },
  props: {
    node: {
      mustUseProp: true,
      default: null,
      type: Object
    }
  },
  computed: {
    formattedNodeData() {
      if (this.currentNode) {
        return [
          { key: 'ID', value: this.currentNode.id },
          { key: '算子', value: this.currentNode.oper },
          { key: '权值', value: this.currentNode.value },
          { key: '权重', value: this.currentNode.weight },
          { key: '父节点ID', value: this.currentNode.father }
        ];
      }
      return [];
    },
    classObje(value) {
      var num = parseFloat(value);
      return (num) => {
        if (num < 0.3){
          return {'color':'#16be60'}
        } else if (num > 0.5){
          return {'color': '#FF0000',}
        } else {
          return {'color':'#DBDB70',}
        }
      }
    }
  },
  data() {
    return {
      myGraphTableSize: { width: window.innerWidth/2-400, height: window.innerHeight-100 },
      myGraphPanelSize: { width: window.innerWidth/2+300, height: window.innerHeight-100 },
      isShowCodePanel: false,
      isShowNodeMenuPanel: false,
      isShowNodeTipsPanel: false,
      dataVisible: false,

      nodeMenuPanelPosition: { x: 0, y: 0 },
      currentNode: {},
      currentSize: 400,

      graphOptions: {
        moveToCenterWhenRefresh: false,
        defaultFocusRootNode: false,
        allowSwitchLineShape: true,
        //allowSwitchJunctionPoint: true,
        //defaultJunctionPoint: 'border',
        isMoveByParentNode: true,
        // 参考"Graph 图谱"中的参数进行设置
        'layouts':[
          {
            'label': '纵向树',
            'layoutName': 'tree',
            'layoutClassName': 'seeks-layout-center',
            useLayoutStyleOptions: true,
            'defaultExpandHolderPosition': 'top',
            'from': 'top',
            'defaultNodeWidth': '200',
            'defaultNodeHeight': '80',
            'defaultJunctionPoint': 'tb',
            'defaultNodeShape': 1,
            'defaultLineShape': 4,
            'defaultNodeBorderWidth': 0,
            'defaultLineColor': 'rgba(0, 186, 189, 1)',
            'defaultNodeColor': 'rgba(0, 206, 209, 1)',
            'min_per_width': 200,
            'max_per_width': 250,
            'min_per_height': 200
          },

          {
            'label': '横向树',
            'layoutName': 'tree',
            'layoutClassName': 'seeks-layout-center',
            useLayoutStyleOptions: true,
            'defaultExpandHolderPosition': 'left',
            'from': 'left',
            'defaultNodeWidth': '198',
            'defaultNodeHeight': '80',
            'defaultJunctionPoint': 'lr',
            'defaultNodeShape': 2,
            'defaultLineShape': 4,
            'defaultNodeBorderWidth': 0,
            'defaultLineColor': '#cccccc',
            'defaultNodeColor': '#43a2f1',
            'min_per_width': 200,
            'max_per_width': 400,
            'min_per_height': 100,
            'max_per_height': 1500
          },
          /*
          {
            'label': '球状',
            'layoutName': 'center',
            'layoutClassName': 'seeks-layout-center',
            useLayoutStyleOptions: true,
            'defaultNodeWidth': '150',
            'defaultNodeHeight': '150',
            defaultNodeBorderWidth: 0,
            defaultNodeColor: 'rgb(161,94,238)',
            defaultLineShape: 3
          },
          */

        ],
      },
      setFa: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 指标管理表格数据
      manageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        indicatorsId: null,
        indicatorsName: null,
        father: null,
        value: null,
        weight: null,
        operator: null,
        indicatorsDesc: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        indicatorsId: [
          { required: true, message: "指标ID不能为空", trigger: "blur" }
        ],
        indicatorsName: [
          { required: true, message: "指标名称不能为空", trigger: "blur" }
        ],
      },
      options: [],
      value: ''
    };
  },
  created() {
  },
  mounted() {
    this.showSeeksGraph();
  },

  methods: {
    showSeeksGraph1() {
      tree_data(this.queryParams).then(response => {
        //console.log(response);
        var __graph_json_data = {
          rootId: '1',
          nodes: [],
          lines: [],
        };

        // 将获取的数据转换为节点对象并添加到__graph_json_data中
        Object.keys(response).forEach(key => {
          const item = response[key];
          //console.log(item);
          __graph_json_data.nodes.push({
            id: item.id.toString(),
            text: item.text.toString(),

            weight: item.weight,
            value: item.value.toString(),
            oper: item.oper.toString(),
            father:item.father.toString(),

            expanded: true,
            data: {
              oper: item.oper,
              weight: item.weight,
              value: item.value,
              isNeedLoadDataFromRemoteServer: true
            }
          });
          if(item.id.toString() !== item.father.toString()){
            __graph_json_data.lines.push({
              from: item.id.toString(),
              to: item.father.toString(),
            });
          }

        });
      })
    },
    showSeeksGraph() {
      tree_data(this.queryParams).then(response => {
        //console.log(response);
        var __graph_json_data = {
          rootId: '1',
          nodes: [],
          lines: [],
        };

        // 将获取的数据转换为节点对象并添加到__graph_json_data中
        Object.keys(response).forEach(key => {
          const item = response[key];
          //console.log(item);
          __graph_json_data.nodes.push({
            id: item.id.toString(),
            text: item.text.toString(),

            weight: item.weight,
            value: item.value.toString(),
            oper: item.oper.toString(),
            father:item.father.toString(),

            expanded: true,
            data: {
              oper: item.oper,
              weight: item.weight,
              value: item.value,
              isNeedLoadDataFromRemoteServer: true
            }
          });
          if(item.id.toString() !== item.father.toString()){
            __graph_json_data.lines.push({
              from: item.id.toString(),
              to: item.father.toString(),
            });
          }
        });
        this.$refs.seeksRelationGraph.setJsonData(__graph_json_data, (graphInstance) => {
          // 这些写上当图谱初始化完成后需要执行的代码
        });
      })


    },

    showNodeMenus(nodeObject, $event) {
      this.currentNode = nodeObject;
      event.preventDefault();
      const _base_position = this.$refs.myPage.getBoundingClientRect();
      //console.log('showNodeMenus:', $event, _base_position);
      this.isShowNodeMenuPanel = true;
      this.nodeMenuPanelPosition.x = $event.clientX - _base_position.x;
      this.nodeMenuPanelPosition.y = $event.clientY - _base_position.y;
    },
    showNodeTips(nodeObject, $event) {
      this.currentNode = nodeObject;
      const _base_position = this.$refs.myPage.getBoundingClientRect();
      //console.log('showNodeMenus:', $event, _base_position);
      //this.isShowNodeTipsPanel = true;
      this.dataVisible = true;
      this.nodeMenuPanelPosition.x = $event.clientX - _base_position.x + 10;
      this.nodeMenuPanelPosition.y = $event.clientY - _base_position.y + 10;
    },
    hideNodeTips(nodeObject, $event) {
      this.currentNode = nodeObject;
      //this.isShowNodeTipsPanel = false;
    },
    doAction(actionName) {
      switch (actionName) {
        case '子节点增加':
          this.doActionAdd(this.currentNode.id);
          this.$notify({
            title: '提示',
            message: '对节点【' + this.currentNode.text + '】进行了：' + actionName,
            type: 'success'
          });
          break;
        case '删除':
          this.doActionDelete(Number(this.currentNode.id));
          break;
        case '配置':
          //this.isShowNodeMenuPanel = false;
          //this.open = true;
          this.doActionModify(Number(this.currentNode.id));
          break;
        case '操作取消':
          this.isShowNodeMenuPanel = false;
          break;
        default:
          // 默认的操作
          break;
      }
      this.isShowNodeMenuPanel = false;
    },
    /** 配置按钮操作 */
    doActionModify(id) {
      this.reset();
      listOperators().then(response => {
        this.options = response.rows;
      });
      const indicatorsId = id;
      getManage(indicatorsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "配置节点信息";
      });
    },
    /** 增加一个默认子节点 */
    doActionAdd(id){
      this.reset();
      addNode(id);
      this.reset();
      this.showSeeksGraph1();
      this.showSeeksGraph1();
      this.showSeeksGraph();
    },
    /** 删除选中节点 */
    doActionDelete(id){
      this.reset();
      const indicatorsId = id;

      this.$modal.confirm('是否确认删除【' + id + '】节点？').then(function() {
        return delManage(indicatorsId);
      }).then(() => {
        this.$notify({
          title: '提示',
          message: '对节点' + id + '进行了：删除操作',
          type: 'success'

        });
        this.showSeeksGraph1();
        this.showSeeksGraph1();
        this.showSeeksGraph();
      }).catch(() => {});

    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "配置节点信息") {
            updateManage(this.form).then(response => {
              //this.$modal.msgSuccess("配置成功");
              this.$notify({
                title: '提示',
                message: '对节点【' +this.form.indicatorsId + '】进行了：节点配置',
                type: 'success'
              });
              this.open = false;
            });
          } else {
            addManage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
            });
          }
        }
      });
      this.showSeeksGraph1();
      this.showSeeksGraph();
    },

    reset() {
      this.form = {
        indicatorsId: null,
        indicatorsName: null,
        father: null,
        value: null,
        weight: null,
        operator: null,
        indicatorsDesc: null
      };
      this.resetForm("form");
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    //节点展开尝试
    onNodeCollapse(node, e) {

      },
    // 通过onNodeExpand事件监听节点的展开事件，在被展开的时候有选择的去从后台获取数据，如果已经从后台加载过数据，则让当前图谱根据当前的节点重新布局
    onNodeExpand(node, e) {
      //console.log('onNodeExpand:', node);
      // 根据具体的业务需要决定是否需要从后台加载数据
      //this.g_loading = true;
      node.data.childrenLoaded = true;
    },

  }
};
</script>

<style lang="scss">

</style>

<style lang="scss" scoped>
.c-node-menu-item{
  line-height: 30px;padding-left: 10px;cursor: pointer;color: #444444;font-size: 14px;border-top:#efefef solid 1px;
}
.c-node-menu-item:hover{
  background-color: rgba(66,187,66,0.2);
}

.c-person-pic{
  width: 120px;
  border-radius: 50%;
  margin-top:10px;
}



.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
